﻿using Core.Framework;
using Core.Framework.Common;
using iTool.Service;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace SocketService
{
    class Program
    {
#if DEBUG
        static readonly string _iToolServiceProcessPath = @"D:\iTool-Cloud-Framework\service.process";
#elif CLOUD
        static readonly string _iToolServiceProcessPath = @"D:\iTool-Cloud-Framework\service.process";
#else
        static readonly string _iToolServiceProcessPath = "/var/iTool/service.process";
#endif
        private static readonly ManualResetEvent manual = new ManualResetEvent(false);
        private static readonly MainProvider provider = new MainProvider(manual);
        private static readonly FileChangeDetect fileChangeDetect = new FileChangeDetect(_iToolServiceProcessPath);

        //systemctl start iToolConnector.service
        //systemctl start iToolServer.service

        //systemctl stop iToolServer.service

        //systemctl status iToolServer.service
        //systemctl status iToolConnector.service

        // journalctl -f | grep "iToolServer"
        // journalctl -f | grep "iToolConnector"

        // journalctl -xe | grep "iToolConnector"

        // rm -rf /var/iTool/iTool-Server
        // git clone https://gitee.com/magey/iTool-Server.git


        static void Main(string[] args)
        {
            // 需要检查 探测器是否启动， 如果探测器启动后（拉去到最新的配置文件后）才可以 继续
            
            try
            {
                // apt-get -y install g++
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Executer.Run("chmod u+x /var/iTool/iTool-Server");
                    Executer.Run("chmod u+x /var/iTool/iTool-Server/insertpackge.sh");
                }

                // 1. 初始化配置文件
                if (!AppSetting.ReSetiToolConfigure())
                {
                    CLog.WriteLineError("\niTool> Please input configinfomation... \n");
                    return;
                }

                // 2. 第一次启动服务
                _ = provider.StartAsync();

                // 3. 注册配置Change事件
                iToolConfigFileChangeDetect
                    .StartAndRegisterChangeEvent(async () => await provider.ReStartAsync(), iToolType.Service);

                // 4. 注册程序注销事件
                Console.CancelKeyPress += async (sender, e) => await provider.StopAsync();
                AppDomain.CurrentDomain.ProcessExit += async (sender, e) => await provider.StopAsync();

                // 5. 注册停止
                fileChangeDetect.StartWaitResult(async value =>
                {
                    LoggerUtils.Write($"StartWaitResult:{value}");
                    if (value == "BeginStoped")
                    {
                        await provider.StopAsync();
                        manual.Set();
                    }
                });

                // 6. Reg Waiting
                manual.WaitOne();

            }
            catch (Exception ex)
            {
                var logger = ProviderOfServices.GetService<ILogger<Program>>();
                logger.LogError(ex, "iTool.Service 退出");
            }
        }
    }
}